<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" show-icon>
      </el-alert>
      <!-- 选择商品分类区 -->
      <el-form>
        <el-form-item label="选择商品分类：">
          <el-cascader v-model="selectCatId" :options="classlist" :props="{ expandTrigger: 'hover', label:'cat_name', value:'cat_id' }" @change="classChange" clearable></el-cascader>
        </el-form-item>
      </el-form>
      <!-- 参数面板区 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加动态参数 -->
          <!-- 按钮 -->
          <el-button type="primary" :disabled="selectCatId.length == 3 ? false : true" @click="dialogManyParamsVisible=true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="paramslist" stripe border style="width: 100%">
            <el-table-column type="expand">
              <!-- 循环tag标签 -->
              <template v-slot:default='scope'>
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" type="primary" closable disable-transitions @close="handleClose(scope.row,index)">{{item}}</el-tag>
                <!-- 添加tag标签 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInputRef" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showTagInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称" min-width="180px">
            </el-table-column>
            <el-table-column label="操作" min-width="180px">
              <template v-slot:default='scope'>
                <!-- 编辑按钮 -->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showModifyParamsDialog(scope.row.attr_id)">编辑</el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加静态属性 -->
          <!-- 按钮 -->
          <el-button type="primary" :disabled="selectCatId.length == 3 ? false : true" @click="dialogOnlyParamsVisible = true">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="paramslist" stripe border style="width: 100%">
            <el-table-column type="expand">
              <!-- 循环tag标签 -->
              <template v-slot:default='scope'>
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" type="primary" closable disable-transitions @close="handleClose(scope.row,index)">{{item}}</el-tag>
                <!-- 添加tag标签 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInputRef" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showTagInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称" min-width="180px">
            </el-table-column>
            <el-table-column label="操作" min-width="180px">
              <template v-slot:default='scope'>
                <!-- 编辑按钮 -->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showModifyParamsDialog(scope.row.attr_id)">编辑</el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加动态参数区域 -->
      <el-dialog title="添加动态参数" :visible.sync="dialogManyParamsVisible" width="50%" @close="resetManyParamsForm">
        <!-- 内容区 -->
        <el-form ref="addManyParamsFormRef" :model="addManyParamsForm" :rules="rules" label-width="80px">
          <el-form-item label="动态参数" prop="attr_name">
            <el-input v-model="addManyParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <!-- 按钮区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogManyParamsVisible = false">取 消</el-button>
          <el-button @click="resetManyParamsForm">重置</el-button>
          <el-button type="primary" @click="addManyParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加静态属性区域 -->
      <el-dialog title="添加静态属性" :visible.sync="dialogOnlyParamsVisible" width="50%" @close="resetOnlyParamsForm">
        <!-- 内容区 -->
        <el-form ref="addOnlyParamsFormRef" :model="addOnlyParamsForm" :rules="rules" label-width="80px">
          <el-form-item label="静态属性" prop="attr_name">
            <el-input v-model="addOnlyParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <!-- 按钮区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogOnlyParamsVisible = false">取 消</el-button>
          <el-button @click="resetOnlyParamsForm">重置</el-button>
          <el-button type="primary" @click="addOnlyParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改参数区域 -->
      <el-dialog :title="'修改' + titleText" :visible.sync="modifyParamsVisible" width="50%" @close="resetModifyParamsForm">
        <!-- 内容区 -->
        <el-form ref="modifyParamsFormRef" :model="modifyParamsForm" :rules="rules" label-width="80px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="modifyParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <!-- 按钮区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="modifyParamsVisible = false">取 消</el-button>
          <el-button @click="resetModifyParamsForm">重置</el-button>
          <el-button type="primary" @click="modifyParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'MyParams',
  data() {
    return {
      classlist: [],
      selectCatId: [],
      activeName: 'many',
      paramslist: [],
      dialogManyParamsVisible: false,
      dialogOnlyParamsVisible: false,
      modifyParamsVisible: false,
      addManyParamsForm: {
        attr_name: '',
        attr_sel: 'many',
        attr_vals: ''
      },
      addOnlyParamsForm: {
        attr_name: '',
        attr_sel: 'only'
      },
      modifyParamsForm: {},
      rules: {
        attr_name: [
          { required: true, message: '请输入动态参数', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  // 计算属性
  computed: {
    // 当前选中的三级分类的Id
    classId() {
      if (this.selectCatId.length === 3) {
        return this.selectCatId[2]
      }
      return null
    },
    // 动态计算标题的文本
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  created() {
    this.getClassList()
  },
  methods: {
    // 获取商品分类数据列表
    async getClassList() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据列表失败！')
      }
      this.classlist = res.data
    },
    // 获取参数列表
    async getParamsList() {
      // 选中的不是第三级分类
      if (this.classId === null) {
        this.paramslist = []
      }
      // 根据所选分类的Id，和当前所处的面板，获取对应的参数
      const { data: res } = await this.$http.get('/categories/' + this.classId + '/attributes', { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败！')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      this.paramslist = res.data
      // console.log(this.paramslist)
    },
    // 级联选择器选择项发生变化时触发——会自动把选择项的value值同步到v-model中，即将cat_id值同步到selectCatId中
    classChange() {
      // console.log(this.selectCatId)
      this.getParamsList()
    },
    // tab标签点击事件
    handleTabClick() {
      // console.log(this.activeName)
      this.getParamsList()
    },
    // 重置添加动态参数表单
    resetManyParamsForm() {
      this.$refs.addManyParamsFormRef.resetFields()
    },
    // 添加动态参数
    addManyParams() {
      this.$refs.addManyParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/categories/' + this.classId + '/attributes', this.addManyParamsForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加动态参数失败！')
        }
        this.$message.success('添加动态参数成功')
        this.dialogManyParamsVisible = false
        this.getParamsList()
      })
    },
    // 重置添加静态属性表单
    resetOnlyParamsForm() {
      this.$refs.addOnlyParamsFormRef.resetFields()
    },
    // 添加静态属性
    addOnlyParams() {
      this.$refs.addOnlyParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/categories/' + this.classId + '/attributes', this.addOnlyParamsForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加静态属性失败！')
        }
        this.$message.success('添加静态属性成功')
        this.dialogOnlyParamsVisible = false
        this.getParamsList()
      })
    },
    // 根据id查询参数
    async showModifyParamsDialog(id) {
      this.modifyParamsVisible = true
      const { data: res } = await this.$http.get('categories/' + this.classId + '/attributes/' + id, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('查询参数失败！')
      }
      this.modifyParamsForm = res.data
      // console.log(this.modifyParamsForm)
    },
    // 重置修改参数表单
    resetModifyParamsForm() {
      this.$refs.modifyParamsFormRef.resetFields()
    },
    // 修改参数
    modifyParams() {
      this.$refs.modifyParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('/categories/' + this.classId + '/attributes/' + this.modifyParamsForm.attr_id, this.modifyParamsForm)
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败！')
        }
        this.$message.success('修改参数成功')
        this.modifyParamsVisible = false
        this.getParamsList()
      })
    },
    // 删除参数
    removeParams(id) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const { data: res } = await this.$http.delete('/categories/' + this.classId + '/attributes/' + id)
          if (res.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
          this.getParamsList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 将对tag参数标签的修改即对attr_vals的操作保存到数据库
    async saveattrVals(row) {
      const { data: res } = await this.$http.put('/categories/' + this.classId + '/attributes/' + row.attr_id, { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) {
        return this.$message.error('修改tag标签失败！')
      }
      this.$message.success('修改tag标签成功')
    },
    // 添加tag参数标签
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length !== 0) {
        row.attr_vals.push(row.inputValue.trim())
      }
      row.inputValue = ''
      row.inputVisible = false
      // console.log(row)
      this.saveattrVals(row)
    },
    showTagInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInputRef.$refs.input.focus()
      })
    },
    // 删除tag参数标签
    async handleClose(row, index) {
      row.attr_vals.splice(index, 1)
      this.saveattrVals(row)
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-cascader {
  width: 260px;
}
.el-tag {
  margin-left: 5px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
